<?php

namespace App\User\Services;
use App\Exceptions\ApiException;
use App\Services\CommonBaseService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;


class WechatService extends CommonBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'wechat:';

    protected $client = null;

    protected $appId = null;
    protected $appSecret = null;
    public function __construct()
    {
        $client = new Client();
        $this->client = $client;
        $this->appId = '';
        $this->appSecret = '';
    }
    public function aesDecrypt($encryptedData, $sessionKey, $iv) {
        // 初始化向量(iv)需要是16字节长度
        $iv = base64_decode($iv);
        // sessionKey需要是32字节长度
        $sessionKey = base64_decode($sessionKey);
        // 加密数据(encryptedData)需要是2的倍数长度
        $encryptedData = base64_decode($encryptedData);
        // 使用OPENSSL_RAW_DATA和AES-128-CBC模式解密
        $decryptedData = openssl_decrypt($encryptedData, 'AES-128-CBC', $sessionKey, OPENSSL_RAW_DATA, $iv);
        // 去除解密后的数据前面的填充字符（PKCS#7）
        $pad = ord($decryptedData[strlen($decryptedData) - 1]);
        $decryptedData = substr($decryptedData, 0, -$pad);
        // 将解密后的数据转换为JSON格式（假设解密后的数据是JSON字符串）
        $decryptedData = json_decode($decryptedData, true);
        return $decryptedData;
    }

    public function getSessionInfo($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        // 准备请求参数
        $formParams = [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        try {
            $options = [
                'form_params' => $formParams
            ];
            $response = $this->client->request('POST', $url, $options);
            // 获取响应体并解码为数组
            $body = json_decode($response->getBody()->getContents(), true);
            if (isset($body['errcode'])) {
                $this->throwApiError($options, json_encode($body['errcode']));
            } else {
                // $openid = $data['openid'];
                // $sessionKey = $data['session_key'];
                return $body;
            }
        } catch (RequestException $e) {
            $this->throwApiError($options, $e->getMessage(), $e->getCode());
        }
    }

    private function throwApiError($options, $error, $code = 200)
    {
        $key = createGuid();
        Log::info('Wechat第三方接口出错key：'.$key);
        Log::info('Wechat第三方接口出错params：'.json_encode($options));
        Log::info('Wechat第三方接口出错：'.$code.'，'.$error);
        throw new ApiException('wechat.error', 'Wechat第三方接口出错：{error}', [
            'error' => $key
        ]);
    }
}
